<?php

namespace catchAdmin\api\controller;

use catchAdmin\api\model\Order as customsOrder;
use catchAdmin\customs\model\XsOrder;
use catchAdmin\api\model\Order as customOrder;
use catchAdmin\customs\model\XsRefund;
use catchAdmin\externalGoods\service\TenantOrderService;
use catcher\CatchResponse;
use catcher\Code;
use thans\jwt\facade\JWTAuth;
use think\Exception;
use think\facade\Db;
use think\helper\Str;
use think\Request;
use xinsheng\api\v1\Pay;

/*
 * 新生支付
 * */
class Xinsheng extends Index
{
    protected $_par = ['_merCode'=>'10000000863',
        '_public_key'=>'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJFkdpM39EbL36SwGUi6LBpXE9kVfX1z4r7NZkJUArJPGkblCs1gW919eAchOZhKOP9eBGAc6KTK0qArujjb+bg69Xl3sqJq0xZJBR1SJbLFI/rV7p0J92crC9ymiGsECM+7DkZS8UXLZeO1aSt59KTgnpfyOX7s4XjMnOS6MbPQIDAQAB'];

    public function xinshengService(Request $request)
    {
        try {
            //获取参数
            $serviceType = $request->param('serviceType');
            $data = $request->post('data');
            //var_dump(file_get_contents('php://input')); //接受row数据
            //写入日志处理
            $this->writeLog('Xinsheng',json_encode($data,JSON_UNESCAPED_UNICODE));

            //验证token
            $auth = JWTAuth::auth();
            $this->merchantInfo = json_decode(json_encode($auth['merchantInfo']),true);//验证token

            if(!$request->has('data','post')){
                return $this->commonReturn('Xinsheng',['code'=>Code::FAILED, 'msg'=>'缺少data']);
            }

            //处理data
            $data = json_decode($data,true);
            if(!$data||!is_array($data)){
                return $this->commonReturn('Xinsheng',['code'=>Code::FAILED, 'msg'=>'data格式错误']);
            }

            //查询子商户 code public
            if('10043' == $this->merchantInfo['tenant_id']){
                $this->_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIxqxcsyOxtdUgYFh49Xbs+wFjpRMYmiyUxxkvq+uHziUWIAOoW0bBnonWx7I358/zQItd7c4rFlidFpoS2XVG/OBTWGVfu8LjSLeSv650ldnDXYSBRtYlI6PqpjHeYxr0vUjiVFnc9yfT0yXiFBHGCDBOKH20P/1LNlvUxexmgwIDAQAB';
                $this->_par['_merCode'] = '10000000889';
            }elseif ('10050' == $this->merchantInfo['tenant_id']){
                $this->_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpnB5TpxPqMZwgarw1xNSTxb2nGeBxlCJ8WwInbeNs52s7w6qBmZJVJN456WoRWeI4mf2WZ7PfVmE+iY+LLjAQ+YZ07A6AI0FtKGIQM4lCtgbjYbi/yCrqwG+Y1odNZkUD+0zHwsJnLEovUx/Ah03Z2wEaY6pidaR+v9ERK/XmiwIDAQAB';
                $this->_par['_merCode'] = '10000000890';
            }elseif ('10143' == $this->merchantInfo['tenant_id']){
                $this->_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCsrshGKOzARNQ65zlZ4izJPUGYTQOINg++2WOZ//ECkmnJqPinSs4ou4NXqnOSBs255JHLO5Xx3d/OXLZ03bg5tUWYSLBkCAAmcBljyMFFOD6hUN8QBd9NAEbspw5uXegqDO/ZAtENwg8bY5at5feagUTEP710jsBgBFkGPnjiXwIDAQAB';
                $this->_par['_merCode'] = '10000000938';
            }elseif ('10144' == $this->merchantInfo['tenant_id']){
                $this->_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTDxEfIEiCZ6DF4xxF45Q2tuz+YXIfneLct4dGrVeyvfJ0SGSF44LVjFbnn2/Zgo6+eOBPtqkk5Xhz0t6UM6owXNBsQ0+f54p8vIDixfDFB1EPYeGrNAD7yneZnRQrVk5C58n6FjRyz8DVa4C94mGf1MPQvt43inEP5K/Sj6hCZQIDAQAB';
                $this->_par['_merCode'] = '10000000937';
            }elseif ('10161' == $this->merchantInfo['tenant_id'] || '10159' == $this->merchantInfo['tenant_id']){
                $this->_par['_public_key'] = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDkLJf6Rh/iQ7VO6jqNzD5AneS++Jh1kkjtbdflXeyBnh70AFGsHgLa70P8TvUfywKqgkY5Vq8+psw7ROhZjyqMqC+rz+M6zpf43R2lvTuCAP3wbbtBdP25QHqIgVTXAVvDcX+YNn+YY2bbB7/IUXurhEOUmEKUOC5YT5cUMSG1XwIDAQAB';
                $this->_par['_merCode'] = '10000001001';
            }

            //方法分发
            switch ($serviceType)
            {
                //提交订单,生成
                case 'apiPay':
                    $result = $this->apiPay($data);
                    break;
                case 'apiPay1':
                    $result = $this->apiPay1($data);
                    break;
                //推送支付单
                case 'customsApply':
                    $result = $this->customsApply($data);
                    break;
                //推送支付单
                case 'customsApply1':
                    $result = $this->customsApply1($data);
                    break;
                //退款
                case 'refund':
                    $result = $this->refund($data);
                    break;
                //查询
                case 'query':
                    $result = $this->query($data);
                    break;
//                case 'query1':
//                    $result = $this->query1($data);
//                    break;
                default:
                    $result = ['code'=>Code::FAILED, 'msg'=>'未定义的服务'];
            }

            return $this->commonReturn("Xinsheng:" . $serviceType,$result);

        } catch (\Exception $exception) {
            return $this->commonReturn("Xinsheng:" . $serviceType,['code'=>Code::FAILED, 'msg'=>$exception->getMessage()]);

        }
    }

    protected function apiPay1($data){
        if(array_key_exists('HNACARD',$data) && $data['HNACARD'] == 1){
            $HNACARD = 1;//使用预付卡支付
            //1.必填字段（微信支付类型）
            $keys = ['tradeType','merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','returnUrl','noticeUrl'];
        }else{
            $HNACARD = 0;
            //1.必填字段（微信支付类型）
            $keys = ['tradeType','merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount',
                'payerAccount','returnUrl','noticeUrl'];
        }

        $data1 = $this->check_fields($data, $keys, true);//验证字段

        if(!is_array($data1)){
            return [ 'code'=>Code::FAILED , 'msg'=> $data1];
        }

        //2.判断交易类型
        $data2 = [];
        if('0004' === $data['tradeType']){//跨境交易
            $keys = ['goodsType','customerName','customerIdNo','customerTel'];
            $data2 = $this->check_fields($data, $keys, true);//验证字段
            if(!is_array($data2)){
                return [ 'code'=>Code::FAILED , 'msg'=> $data2];
            }
            $data2['customerType'] = "1"; //个人
        }
        $data = array_merge($data1,$data2);

        if($HNACARD){//如果是预付卡订单，需要提前将订单推送过来
//            //判断订单是否已经过来
//            $where = [
//                'tenant_id'=>$this->merchantInfo['tenant_id'],
//                'orderId'=>$data['merOrderId']
//            ];
//            $order  = (new customsOrder)
//                ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
//                ->where($where)
//                ->find();
//
//            if(!$order){//不存在
//                return [ 'code'=>Code::FAILED , 'msg'=> "预付卡订单，请先订单推到平台中"];
//            }
//            $value = $order->toArray();
//
//            if('0002' == $value['tradeType'] || '0' == $value['is_need_push_payment_order']){
//                return [ 'code'=>Code::FAILED , 'msg'=> "该订单贸易类型无需使用预付卡支付"];
//            }

            $data['payType'] = '10';//预付卡
            $data['orgCode'] = 'HNACARD';//预付卡
        }else{
            //默认参数
//            if('10043' == $this->merchantInfo['tenant_id']){//云级
//                $data['payType'] = "4"; //扫码
//            }else{
//                $data['payType'] = "5"; //小程序
//            }
            $data['payType'] = "5"; //小程序
            $data['orgCode'] = "WECHATPAY";
        }

        //3.实例化新生api
        $xinshengApi = new Pay($this->_par);

        //保存通知客户的回掉地址
        $toReturnUrl = $data['returnUrl'];$toNoticeUrl = $data['noticeUrl'];


        $data['orderCurrencyCode'] = "CNY";
        $data['payCurrencyCode'] = "CNY";
        $data['settleCurrencyCode'] = "CNY";
        $data['shareFlag'] = "0"; //不分账
        $data['declareCheck'] = "0"; //验证
        $data['returnUrl'] = "http://cross.qekj.net/callback/xinsheng";
        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";

        //文档参数顺序
        $req_key = ['merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','orderCurrencyCode','tradeType',
            'payType','orgCode','payerAccount','payCurrencyCode','settleCurrencyCode','shareFlag','subMerchantOrderDetails','returnUrl',
            'noticeUrl','platformId','customerId','customerType','customerName','customerIdNo','customerTel'
            ,'bankCardNo','bankCardType','expireData','cvn','remark','reserve1','reserve2','preOrderFlag','declareCheck'];
        //新生支付，参数有顺序要求。必须按照文档来
        $data = getAfterSortByKeys($req_key,$data);

//        dump($data);die();

//        unset($data['returnUrl'],$data['noticeUrl']);
//
//        $data = [
//            'merOrderId'=>Str::random(20,1),
//            'displayName'=>"面膜",
//            'goodsName'=>"面膜",
//            'goodsCount'=>1,
//            'goodsType'=>"06",
//            'orderAmount'=>100,
//            'orderCurrencyCode'=>"CNY",
//            'tradeType'=>"0004",
//            'payType'=>"4",
//            'orgCode'=>'alipay',
//            'payCurrencyCode'=>"CNY",
//            'settleCurrencyCode'=>"CNY",
//            'shareFlag'=>"0",
//            'returnUrl'=>"http://cross.qekj.net/callback/xinsheng",
//            'noticeUrl'=>"http://cross.qekj.net/callback/xinsheng",
//            'customerType'=>"1",
//            'customerName'=>'徐颖',
//            'customerIdNo'=>'320923199610233610',
//            'customerTel'=>'15150688887'
//        ];

//        //查找是否存在
//        $order  = (new XsOrder)
//            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
//            ->where('merOrderId',$data['merOrderId'])
//            ->find();
////        if($order){
////            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}已存在"];
////        }

        try {
            $result = $xinshengApi->apiPay($data);//支付接口返回数据

            $this->writeLog('xinshengTestapi2221','5555');
            //print_r(json_encode($result,JSON_UNESCAPED_UNICODE));

            $insert_merge =  [
                '_ext_data'=>$data,
                '_return_data'=>$result['content'],//接口返回内容保存一份
                'status'=>$result['content']['status'],//支付状态
                'dealId'=>$result['content']['dealId'],//支付系统交易号
                'orderId'=>$result['head']['orderId'],
                'tenant_id'=>$this->merchantInfo['tenant_id'],
                'toReturnUrl'=>$toReturnUrl,//客户回掉地址
                'toNoticeUrl'=>$toNoticeUrl,//客户回掉地址
            ];

            if($HNACARD){
                //预付卡独有参数
                $insert_merge['payAmount'] = number_format($result['content']['payAmount'] / 100 ,2);
                $insert_merge['completeTime'] = $result['content']['completeTime'];

                $update =  [
                    'pay_time'=>time(),
//                    'push_status'=>'已支付',
                    'push_status'=>'未推送',
//                'xs_status'=>$result['content']['status'],
                    'dealId'=>$result['content']['dealId'],
                    'payOrderNo'=>$result['content']['dealId'],
//                '_random_orderId'=>$result['head']['orderId']
                ];
                //$order->save($update);
            }else{
                $insert_merge['payInfo'] = $result['content']['payInfo'];//用于小程序的支付参数
            }

            //合并参数
            $insert = array_merge($data,$insert_merge);

            $last_result = $result['content'];
            $last_result['initialRequest'] = $data;//原始请求
            $last_result['initialResponse'] = $result;//原始响应

            $suc = (new XsOrder)->save($insert);
            if($suc) return [ 'code'=>Code::SUCCESS , 'msg'=> '创建成功' , 'data'=>$last_result];
            else return [ 'code'=>Code::FAILED , 'msg'=> '创建失败'];
        }catch (\Exception $e ){
            $this->writeLog('apiPayError',json_encode($data,JSON_UNESCAPED_UNICODE));
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }


    //提交订单
    protected function apiPay($data){
        $reserve2 = $data['reserve2'] ?? '';
        if(array_key_exists('HNACARD',$data) && $data['HNACARD'] == 1){
            $HNACARD = 1;//使用预付卡支付
            //1.必填字段（微信支付类型）
            $keys = ['tradeType','merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','returnUrl','noticeUrl'];
        }else{
            $HNACARD = 0;
            //1.必填字段（微信支付类型）
            $keys = ['tradeType','merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount',
                'payerAccount','returnUrl','noticeUrl'];
        }

        $data1 = $this->check_fields($data, $keys, true);//验证字段

        if(!is_array($data1)){
            return [ 'code'=>Code::FAILED , 'msg'=> $data1];
        }

        //2.判断交易类型
        $data2 = [];
        if('0004' === $data['tradeType']){//跨境交易
            $keys = ['goodsType','customerName','customerIdNo','customerTel'];
            $data2 = $this->check_fields($data, $keys, true);//验证字段
            if(!is_array($data2)){
                return [ 'code'=>Code::FAILED , 'msg'=> $data2];
            }
            $data2['customerType'] = "1"; //个人
        }
        $data2['reserve2'] = $reserve2;
        $data = array_merge($data1,$data2);

        if($HNACARD){//如果是预付卡订单，需要提前将订单推送过来
            //判断订单是否已经过来
            $where = [
                'tenant_id'=>$this->merchantInfo['tenant_id'],
                'orderId'=>$data['merOrderId']
            ];
            $order  = (new customsOrder)
                ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
                ->where($where)
                ->find();

            if(!$order){//不存在
                return [ 'code'=>Code::FAILED , 'msg'=> "预付卡订单，请先订单推到平台中"];
            }
            $value = $order->toArray();

            if('0002' == $value['tradeType'] || '0' == $value['is_need_push_payment_order']){
                return [ 'code'=>Code::FAILED , 'msg'=> "该订单贸易类型无需使用预付卡支付"];
            }

            $data['payType'] = '10';//预付卡
            $data['orgCode'] = 'HNACARD';//预付卡
        }else{
            //默认参数
//            if('10144' == $this->merchantInfo['tenant_id']){//丝路电商


//            if(in_array($this->merchantInfo['tenant_id'] , [10144 , 10161])){
            if(in_array($this->merchantInfo['tenant_id'] , [10144])){
                $data['payType'] = "4"; //扫码
            }else{
                $data['payType'] = "5"; //小程序
            }
            //$data['payType'] = "5"; //小程序
            $data['orgCode'] = "WECHATPAY";
        }


        //处理半屏参数 文商跨境
        if(in_array($this->merchantInfo['tenant_id'] , [10161,10159])){
            $data['orgCode'] = "HNACASHIER"; //HNACASHIER
        }


        //3.实例化新生api
        $xinshengApi = new Pay($this->_par);

        //保存通知客户的回掉地址
        $toReturnUrl = $data['returnUrl'];$toNoticeUrl = $data['noticeUrl'];


        $data['orderCurrencyCode'] = "CNY";
        $data['payCurrencyCode'] = "CNY";
        $data['settleCurrencyCode'] = "CNY";
        $data['shareFlag'] = "0"; //不分账
        $data['declareCheck'] = "0"; //验证
        $data['returnUrl'] = "http://cross.qekj.net/callback/xinsheng";
        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";

        //文档参数顺序
        $req_key = ['merOrderId','displayName','goodsName','goodsCount','goodsType','orderAmount','orderCurrencyCode','tradeType',
            'payType','orgCode','payerAccount','payCurrencyCode','settleCurrencyCode','shareFlag','subMerchantOrderDetails','returnUrl',
            'noticeUrl','platformId','customerId','customerType','customerName','customerIdNo','customerTel'
        ,'bankCardNo','bankCardType','expireData','cvn','remark','reserve1','reserve2','preOrderFlag','declareCheck'];
        //新生支付，参数有顺序要求。必须按照文档来
        $data = getAfterSortByKeys($req_key,$data);

//        unset($data['returnUrl'],$data['noticeUrl']);
//
//        $data = [
//            'merOrderId'=>Str::random(20,1),
//            'displayName'=>"面膜",
//            'goodsName'=>"面膜",
//            'goodsCount'=>1,
//            'goodsType'=>"06",
//            'orderAmount'=>100,
//            'orderCurrencyCode'=>"CNY",
//            'tradeType'=>"0004",
//            'payType'=>"4",
//            'orgCode'=>'alipay',
//            'payCurrencyCode'=>"CNY",
//            'settleCurrencyCode'=>"CNY",
//            'shareFlag'=>"0",
//            'returnUrl'=>"http://cross.qekj.net/callback/xinsheng",
//            'noticeUrl'=>"http://cross.qekj.net/callback/xinsheng",
//            'customerType'=>"1",
//            'customerName'=>'徐颖',
//            'customerIdNo'=>'320923199610233610',
//            'customerTel'=>'15150688887'
//        ];

//        //查找是否存在
//        $order  = (new XsOrder)
//            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
//            ->where('merOrderId',$data['merOrderId'])
//            ->find();
////        if($order){
////            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}已存在"];
////        }



        /**

        $a = json_decode('{
	"responseCode": "0000",
	"responseDesc": "请求处理成功",
	"merOrderId": "240530104947900601",
	"dealId": "1022405301052025006",
	"payType": "10",
	"orderAmount": 5200,
	"orderCurrency": "CNY",
	"payAmount": 5200,
	"payCurrency": "CNY",
	"settleCurrency": "CNY",
	"status": "1",
	"completeTime": "20240530105211"
}',true);

        //dump($a);die();

        $insert_merge =  [
            '_ext_data'=>$data,
            '_return_data'=>$a,//接口返回内容保存一份
            'status'=>$a['status'],//支付状态
            'dealId'=>$a['dealId'],//支付系统交易号
            'orderId'=>'0',
            'tenant_id'=>$this->merchantInfo['tenant_id'],
            'toReturnUrl'=>$toReturnUrl,//客户回掉地址
            'toNoticeUrl'=>$toNoticeUrl,//客户回掉地址
        ];

        if($HNACARD){
            //预付卡独有参数
            $insert_merge['payAmount'] = number_format($a['payAmount'] / 100 ,2);
            $insert_merge['completeTime'] = $a['completeTime'];

            $update =  [
                'pay_time'=>time(),
//                    'push_status'=>'已支付',
                'push_status'=>'未推送',
//                'xs_status'=>$result['content']['status'],
                'dealId'=>$a['dealId'],
                'payOrderNo'=>$a['dealId'],
//                '_random_orderId'=>$result['head']['orderId']
            ];
            $order->save($update);
        }else{
            $insert_merge['payInfo'] = $a['payInfo'];//用于小程序的支付参数
        }

        //合并参数
        $insert = array_merge($data,$insert_merge);

        $last_result = $a;
        $last_result['initialRequest'] = $data;//原始请求
        $last_result['initialResponse'] = $a;//原始响应

        $suc = (new XsOrder)->save($insert);


        dd(333);

**/

        try {
            $result = $xinshengApi->apiPay($data);//支付接口返回数据



            $insert_merge =  [
                '_ext_data'=>$data,
                '_return_data'=>$result['content'],//接口返回内容保存一份
                'status'=>$result['content']['status'],//支付状态
                'dealId'=>$result['content']['dealId'],//支付系统交易号
                'orderId'=>$result['head']['orderId'],
                'tenant_id'=>$this->merchantInfo['tenant_id'],
                'toReturnUrl'=>$toReturnUrl,//客户回掉地址
                'toNoticeUrl'=>$toNoticeUrl,//客户回掉地址
            ];

            if($HNACARD){
                //预付卡独有参数
                $insert_merge['payAmount'] = number_format($result['content']['payAmount'] / 100 ,2);
                $insert_merge['completeTime'] = $result['content']['completeTime'];

                $update =  [
                    'pay_time'=>time(),
//                    'push_status'=>'已支付',
                    'push_status'=>'未推送',
//                'xs_status'=>$result['content']['status'],
                    'dealId'=>$result['content']['dealId'],
                    'payOrderNo'=>$result['content']['dealId'],
//                '_random_orderId'=>$result['head']['orderId']
                ];
                $order->save($update);
            }else{
                $insert_merge['payInfo'] = $result['content']['payInfo'];//用于小程序的支付参数
            }

            //合并参数
            $insert = array_merge($data,$insert_merge);

            $last_result = $result['content'];
            $last_result['initialRequest'] = $data;//原始请求
            $last_result['initialResponse'] = $result;//原始响应

            $suc = (new XsOrder)->save($insert);
            if($suc) return [ 'code'=>Code::SUCCESS , 'msg'=> '创建成功' , 'data'=>$last_result];
            else return [ 'code'=>Code::FAILED , 'msg'=> '创建失败'];
        }catch (\Exception $e ){
            $this->writeLog('apiPayError',json_encode($data,JSON_UNESCAPED_UNICODE));
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }


    //推送支付单1
    protected function customsApply1($data){
        //1.必填字段
        $keys = ['merOrderId','eCompanyCode','eCompanyName',
            'payTransactionNo','actionType','payerName','payerType','payerId','noticeUrl'];
        $data = $this->check_fields($data, $keys, true);//验证字段
        if(!is_array($data)){
            return [ 'code'=>Code::FAILED , 'msg'=> $data];
        }

        //查看新生订单是否存在
        $order  = (new XsOrder)
            ->alias('xs')
            ->leftJoin('db_customs_order cs','cs.orderId = xs.merOrderId')
            ->where('xs.tenant_id', $this->merchantInfo['tenant_id'])
            ->where('xs.merOrderId',$data['merOrderId'])
            ->field('cs.id as custom_pk,xs.id as xs_pk')->find();

//        if(!$order){
//            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}不存在"];
//        }
//        //查看订单是否推送到平台
//        if(!$order->custom_pk){
//            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}的订单没有推到平台中"];
//        }
//
//        $c_order = (new \catchAdmin\customs\model\Order())->where('orderId',$data['merOrderId'])->find();
//        if('0002' == $c_order->tradeType || '0' == $c_order->is_need_push_payment_order){
//            return [ 'code'=>Code::FAILED , 'msg'=> "该订单贸易类型无需推送支付单"];
//        }
        //return [ 'code'=>Code::SUCCESS , 'msg'=> "可以申请报关请求",'data'=>[]];

        //保存商户回掉地址
        $toNoticeUrl2 = $data['noticeUrl'];

        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";
        $data['currencyCode'] = 'CNY';
        $data['eportCode'] = '00';//统一版


        //文档参数顺序
        $req_key = ['eportCode','merOrderId','currencyCode','eCompanyCode','eCompanyName','payTransactionNo','actionType','payerName','payerType','payerId','payerPhoneNumber','orderDetails','noticeUrl'];
        //新生支付，参数有顺序要求。必须按照文档来
        $data = getAfterSortByKeys($req_key,$data);

        //dump($data);die();

        $data['actionType'] = (string) $data['actionType'];

        //实例化新生api类
        $xinshengApi = new Pay($this->_par);

        Db::startTrans();
        try {
//            $orderService = new TenantOrderService();
//            $creditDeductResult = $orderService->creditDeductByOrderPk($c_order['id']);
//            if($creditDeductResult['status'] != 1){// 授信额度扣款失败了
//                throw new Exception($creditDeductResult['msg']);
//            }

            $result = $xinshengApi->customsApply($data);
            $order1 = (new XsOrder)->find($order->xs_pk);
            $order1->customsApply_param = $data;//报关请求参数
            $order1->customsApply_return = $result['content'];//报关同步返回的参数
            $order1->customsApply_status = 1;//已申请
            $order1->toNoticeUrl2 = $toNoticeUrl2;//报关申请-异步通知地址

            $suc =  $order1->save();
            if($suc) {
                Db::commit();
                return ['code' => Code::SUCCESS, 'msg' => '提交成功', 'data' => $result['content']];
            }else{
                throw new Exception('提交失败');
            }
        }catch (\Exception $e ){
            Db::rollback();
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }

    //推送支付单
    protected function customsApply($data){
        //1.必填字段
        $keys = ['merOrderId','eCompanyCode','eCompanyName',
            'payTransactionNo','actionType','payerName','payerType','payerId','noticeUrl'];
        $data = $this->check_fields($data, $keys, true);//验证字段
        if(!is_array($data)){
            return [ 'code'=>Code::FAILED , 'msg'=> $data];
        }

        //查看新生订单是否存在
        $order  = (new XsOrder)
            ->alias('xs')
            ->leftJoin('db_customs_order cs','cs.orderId = xs.merOrderId')
            ->where('xs.tenant_id', $this->merchantInfo['tenant_id'])
            ->where('xs.merOrderId',$data['merOrderId'])
            ->field('cs.id as custom_pk,xs.id as xs_pk')->find();

        if(!$order){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}不存在"];
        }
        //查看订单是否推送到平台
        if(!$order->custom_pk){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['merOrderId']}的订单没有推到平台中"];
        }

        $c_order = (new \catchAdmin\customs\model\Order())->where('orderId',$data['merOrderId'])->find();
        if('0002' == $c_order->tradeType || '0' == $c_order->is_need_push_payment_order){
            return [ 'code'=>Code::FAILED , 'msg'=> "该订单贸易类型无需推送支付单"];
        }
        //return [ 'code'=>Code::SUCCESS , 'msg'=> "可以申请报关请求",'data'=>[]];

        //保存商户回掉地址
        $toNoticeUrl2 = $data['noticeUrl'];

        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";
        $data['currencyCode'] = 'CNY';
        $data['eportCode'] = '00';//统一版


        //文档参数顺序
        $req_key = ['eportCode','merOrderId','currencyCode','eCompanyCode','eCompanyName','payTransactionNo','actionType','payerName','payerType','payerId','payerPhoneNumber','orderDetails','noticeUrl'];
        //新生支付，参数有顺序要求。必须按照文档来
        $data = getAfterSortByKeys($req_key,$data);

        $data['actionType'] = (string) $data['actionType'];

        //实例化新生api类
        $xinshengApi = new Pay($this->_par);

        Db::startTrans();
        try {
            $orderService = new TenantOrderService();
            $creditDeductResult = $orderService->creditDeductByOrderPk($c_order['id']);
            if($creditDeductResult['status'] != 1){// 授信额度扣款失败了
                throw new Exception($creditDeductResult['msg']);
            }

            $result = $xinshengApi->customsApply($data);
            $order1 = (new XsOrder)->find($order->xs_pk);
            $order1->customsApply_param = $data;//报关请求参数
            $order1->customsApply_return = $result['content'];//报关同步返回的参数
            $order1->customsApply_status = 1;//已申请
            $order1->toNoticeUrl2 = $toNoticeUrl2;//报关申请-异步通知地址

            $suc =  $order1->save();
            if($suc) {
                Db::commit();
                return ['code' => Code::SUCCESS, 'msg' => '提交成功', 'data' => $result['content']];
            }else{
                throw new Exception('提交失败');
            }
        }catch (\Exception $e ){
            Db::rollback();
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }

    //退款
    protected function refund($data){
        $keys = ['merOrderId','oldDealId','amount','currency','noticeUrl'];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数
        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        $order  = (new XsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('dealId',$data['oldDealId'])
            ->find();

        $refund = (new XsRefund)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('merOrderId',$data['merOrderId'])
            ->find();

        if(!$order){
            return [ 'code'=>Code::FAILED , 'msg'=> "支付交易号{$data['oldDealId']}不存在"];
        }

        if($refund){
            return [ 'code'=>Code::FAILED , 'msg'=> "退款订单编号{$data['merOrderId']}已存在"];
        }

        $xinshengApi = new Pay($this->_par);
        $data['noticeUrl'] = "http://cross.qekj.net/callback/xinsheng";

        try {
            $orderId = Str::random(20,1);
            $result = $xinshengApi->refund($orderId,$data);
            $refundData = [
                'orderId'=>$orderId,
                'merOrderId'=>$data['merOrderId'],
                'oldDealId'=>$data['oldDealId'],
                'status'=>$result['content']['status'],
                'responseDesc'=>$result['content']['responseDesc'],
                'refundOrderNo'=>$result['content']['refundOrderNo'],
                'oldOrderAmount'=>$result['content']['oldOrderAmount'],
                'refundAmount'=>$result['content']['refundAmount'],
                'refundFee'=>$result['content']['refundFee'],
                'tenant_id'=>$this->merchantInfo['tenant_id'],
                '_return_data'=>$result['content']
            ];

            $refundModel = (new XsRefund)->save($refundData);

            return [ 'code'=>Code::SUCCESS , 'msg'=> '退款申请成功' , 'data'=>$result];
        }catch (\Exception $e ){
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }

    //查询
    protected function query($data){
        $keys = ['queryType','orderType','oldMerOrderId','startTime','endTime','page'];
        $value = $this->check_fields($data, $keys, true);//验证字段
        //判断参数
        if(!is_array($value)){
            return [ 'code'=>Code::FAILED , 'msg'=> $value];
        }

        if(1 == $data['queryType']){//单笔订单
            if(empty($data['oldMerOrderId']))  return [ 'code'=>Code::FAILED , 'msg'=> 'oldMerOrderId不能为空'];

        }

        $order  = (new XsOrder)
            ->withoutField('created_at,updated_at,deleted_at,tenant_id,creator_id')
            ->where('merOrderId',$data['oldMerOrderId'])
            ->find();

        if(!$order){
            return [ 'code'=>Code::FAILED , 'msg'=> "订单编号{$data['oldMerOrderId']}不存在"];
        }

        $xinshengApi = new Pay($this->_par);

        try {
            $result = $xinshengApi->orderQuery($data);

            return [ 'code'=>Code::SUCCESS , 'msg'=> '查询成功' , 'data'=>$result['content']];
        }catch (\Exception $e ){
            return [ 'code'=>Code::FAILED , 'msg'=> $e->getMessage()];
        }
    }


}